package cn.it.shop.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.stereotype.Component;

import cn.it.shop.service.EmailUtil;

@Component("emailUtil")
public class EmailUtilImpl implements EmailUtil {
	// 发送带图片的多媒体邮件
	
	@Override
	public String getOneHtml(final String htmlurl) throws Exception {
		URL url;
		String temp;
		StringBuffer sb = new StringBuffer();
		url = new URL(htmlurl);
		BufferedReader in = new BufferedReader(new InputStreamReader(url
				.openStream(), "UTF-8"));// 读取网页全部内容
		while ((temp = in.readLine()) != null) {
			sb.append(temp);
		}
		System.out.println(sb.toString());
		return sb.toString();
	}
	
	@Override
	public void sendMessage(int id,String address){
		Properties props=new Properties();
		// 指定邮件传输协议
		props.setProperty("mail.transport.protocol", "smtp");
		// 1: 创建会话(session)
		Session session=null;
		Message message=null;
		Transport transport=null;
		try {
			session=Session.getDefaultInstance(props);
			session.setDebug(true);
			// 2: 创建邮件对象,并且填写邮件相关信息
			message=new MimeMessage(session);
			// 发件人邮箱地址
			message.setFrom(new InternetAddress("soft03_test@sina.com"));
			// 填写邮件主题
			message.setSubject("订单支付成功邮件");
			// 填写邮件内容
			message.setContent("订单" + id + "已经支付成功!","text/html;charset=UTF-8");
			// 3: 创建邮件发送对象
			transport = session.getTransport();
			// smtp默认的端口是25
			transport.connect("smtp.sina.com",25,"soft03_test", "soft03_test");
			// 4: 发送邮件(填写邮件对象,接收人的地址),并且释放资源
			transport.sendMessage(message,new Address[]{new InternetAddress(address)});
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			try {
				transport.close();
			} catch (MessagingException e) {
				throw new RuntimeException(e);
			}
		}
		
	}
}
